package jnpf.permission.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jnpf.base.UserInfo;
import jnpf.base.controller.SuperController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.annotation.OrganizeAdminIsTrator;
import jnpf.base.ActionResult;
import jnpf.base.entity.*;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.base.service.*;
import jnpf.constant.MsgCode;
import jnpf.permission.constant.AuthorizeConst;
import jnpf.permission.entity.*;
import jnpf.permission.mapper.AuthorizeMapper;
import jnpf.permission.model.authorize.*;
import jnpf.permission.model.columnspurview.ColumnsPurviewUpForm;
import jnpf.permission.service.*;
import jnpf.util.*;
import jnpf.util.treeutil.ListToTreeUtil;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 操作权限
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Tag(name = "操作权限", description = "Authorize")
@RestController
@RequestMapping("/api/permission/Authority")
public class AuthorizeController extends SuperController<AuthorizeService, AuthorizeEntity> {

    @Autowired
    private ModuleService moduleApi;
    @Autowired
    private ModuleButtonService buttonApi;
    @Autowired
    private ModuleColumnService columnApi;
    @Autowired
    private ModuleFormService formApi;
    @Autowired
    private ModuleDataAuthorizeSchemeService schemeApi;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private ColumnsPurviewService columnsPurviewService;
    @Autowired
    private PermissionGroupService permissionGroupService;
    @Autowired
    private AuthorizeMapper authorizeMapper;


    /**
     * 权限数据
     *
     * @param objectId 对象主键
     * @param dataValuesQuery 权限值
     * @return
     */
    @Operation(summary = "获取岗位/角色/用户权限树形结构")
    @Parameters({
            @Parameter(name = "objectId", description = "对象主键", required = true),
            @Parameter(name = "dataValuesQuery", description = "权限值", required = true)
    })
    @SaCheckPermission(value = {"permission.authorize", "permission.role"}, mode = SaMode.OR)
    @PostMapping("/Data/{objectId}/Values")
    public ActionResult<AuthorizeDataReturnVO> getValuesData(@PathVariable("objectId") String objectId, @RequestBody DataValuesQuery dataValuesQuery) {
        AuthorizeVO authorizeModel = authorizeService.getAuthorize(true, false);
        List<AuthorizeEntity> list = authorizeService.list(new QueryWrapper<AuthorizeEntity>().lambda().eq(AuthorizeEntity::getObjectId, objectId));
        if (!StringUtil.isEmpty(dataValuesQuery.getType())) {
            switch (dataValuesQuery.getType()) {
                case "system":
                    AuthorizeDataReturnVO authorizeDataReturnVO = this.system(list, authorizeModel);
                    return ActionResult.success(authorizeDataReturnVO);
                case "module":
                    List<String> systemId = new ArrayList<>();
                    if (!StringUtil.isEmpty(dataValuesQuery.getModuleIds())) {
                        systemId = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                    }
                    List<ModuleEntity> moduleList = moduleApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    AuthorizeDataReturnVO dataReturnVO = this.module1(moduleList, list, authorizeModel, systemId);
                    return ActionResult.success(dataReturnVO);
                case "button":
                    List<ModuleEntity> moduleList1 = moduleApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList1 = new ArrayList<>();
                    if (!StringUtil.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId1 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList1 = moduleList1.stream().filter(t -> moduleId1.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleButtonEntity> moduleButtonList = buttonApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    AuthorizeDataReturnVO dataReturnVo1 = this.moduleButton(selectList1, moduleButtonList, list, authorizeModel);
                    return ActionResult.success(dataReturnVo1);

                case "column":
                    List<ModuleEntity> moduleList2 = moduleApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList2 = new ArrayList<>();
                    if (!StringUtil.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId2 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList2 = moduleList2.stream().filter(t -> moduleId2.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleColumnEntity> moduleColumnList = columnApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    AuthorizeDataReturnVO dataReturnVo2 = this.moduleColumn(selectList2, moduleColumnList, list, authorizeModel);
                    return ActionResult.success(dataReturnVo2);

                case "resource":
                    List<ModuleEntity> moduleList3 = moduleApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList3 = new ArrayList<>();
                    if (!StringUtil.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId3 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList3 = moduleList3.stream().filter(t -> moduleId3.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleDataAuthorizeSchemeEntity> moduleDataSchemeList = schemeApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    AuthorizeDataReturnVO dataReturnVo3 = this.resourceData(selectList3, moduleDataSchemeList, list, authorizeModel);
                    return ActionResult.success(dataReturnVo3);

                case "form":
                    List<ModuleEntity> moduleList4 = moduleApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    //挑选出的list
                    List<ModuleEntity> selectList4 = new ArrayList<>();
                    if (!StringUtil.isEmpty(dataValuesQuery.getModuleIds())) {
                        List<String> moduleId4 = Arrays.asList(dataValuesQuery.getModuleIds().split(","));
                        selectList4 = moduleList4.stream().filter(t -> moduleId4.contains(t.getId())).collect(Collectors.toList());
                    }
                    List<ModuleFormEntity> moduleFormList = formApi.getList().stream().filter(
                            m -> "1".equals(String.valueOf(m.getEnabledMark()))
                    ).collect(Collectors.toList());
                    AuthorizeDataReturnVO dataReturnVo4 = this.moduleForm(selectList4, moduleFormList, list, authorizeModel);
                    return ActionResult.success(dataReturnVo4);

                default:
            }
        }
        return ActionResult.fail("类型不能为空");
    }


    /**
     * 对象数据
     *
     * @return
     */
    @Operation(summary = "获取功能权限数据")
    @Parameters({
            @Parameter(name = "itemId", description = "对象主键", required = true),
            @Parameter(name = "objectType", description = "对象类型", required = true)
    })
    @SaCheckPermission(value = {"permission.authorize", "permission.role", "onlineDev.visualPortal"}, mode = SaMode.OR)
    @GetMapping("/Model/{itemId}/{objectType}")
    public ActionResult<AuthorizeItemObjIdsVO> getObjectAuth(@PathVariable("itemId") String itemId, @PathVariable("objectType") String objectType) {
        List<AuthorizeEntity> authorizeList = authorizeService.getListByObjectAndItem(itemId, objectType);
        List<String> ids = authorizeList.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
        AuthorizeItemObjIdsVO vo = new AuthorizeItemObjIdsVO();
        vo.setIds(ids);
        return ActionResult.success(vo);
    }

    @Operation(summary = "门户管理授权")
    @Parameters({
            @Parameter(name = "itemId", description = "对象主键", required = true),
            @Parameter(name = "saveAuthForm", description = "保存权限模型", required = true)})
    @PutMapping("/Model/{portalManageId}")
    @SaCheckPermission(value = {"permission.authorize", "permission.role"}, mode = SaMode.OR)
    public ActionResult<String> savePortalManage(@PathVariable("portalManageId") String portalManageId, @RequestBody SaveAuthForm saveAuthForm) {
        authorizeService.savePortalManage(portalManageId, saveAuthForm);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 保存
     *
     * @param objectId 对象主键
     * @param authorizeDataUpForm 修改权限模型
     * @return
     */
    @OrganizeAdminIsTrator
    @Operation(summary = "保存权限")
    @Parameters({
            @Parameter(name = "objectId", description = "对象主键", required = true),
            @Parameter(name = "authorizeDataUpForm", description = "修改权限模型", required = true)
    })
    @SaCheckPermission(value = {"permission.authorize", "permission.role"}, mode = SaMode.OR)
    @PutMapping("/Data/{objectId}")
    public ActionResult save(@PathVariable("objectId") String objectId, @RequestBody AuthorizeDataUpForm authorizeDataUpForm) {
        authorizeService.save(objectId, authorizeDataUpForm);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 保存批量
     *
     * @param saveBatchForm 批量保存模型
     * @return
     */
    @OrganizeAdminIsTrator
    @Operation(summary = "批量保存权限")
    @Parameters({
            @Parameter(name = "saveBatchForm", description = "批量保存模型", required = true)
    })
    @SaCheckPermission(value = {"permission.authorize"}, mode = SaMode.OR)
    @PostMapping("/Data/Batch")
    public ActionResult saveBatch(@RequestBody SaveBatchForm saveBatchForm) {
        authorizeService.saveBatch(saveBatchForm, true);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 获取模块列表展示字段
     *
     * @param moduleId 菜单Id
     * @return
     */
    @Operation(summary = "获取模块列表展示字段")
    @Parameters({
            @Parameter(name = "moduleId", description = "菜单id", required = true)
    })
    @GetMapping("/GetColumnsByModuleId/{moduleId}")
    public ActionResult getColumnsByModuleId(@PathVariable("moduleId") String moduleId) {
        ColumnsPurviewEntity entity = columnsPurviewService.getInfo(moduleId);
        List<Map<String, Object>> jsonToListMap = null;
        if (entity != null) {
            jsonToListMap = JsonUtil.getJsonToListMap(entity.getFieldList());
        }
        return ActionResult.success(jsonToListMap != null ? jsonToListMap : new ArrayList<>(16));
    }

    /**
     * 配置模块列表展示字段
     *
     * @param columnsPurviewUpForm 修改模型
     * @return
     */
    @Operation(summary = "配置模块列表展示字段")
    @Parameters({
            @Parameter(name = "columnsPurviewUpForm", description = "修改模型", required = true)
    })
    @PutMapping("/SetColumnsByModuleId")
    public ActionResult setColumnsByModuleId(@RequestBody ColumnsPurviewUpForm columnsPurviewUpForm) {
        ColumnsPurviewEntity entity = JsonUtil.getJsonToBean(columnsPurviewUpForm, ColumnsPurviewEntity.class);
        columnsPurviewService.update(columnsPurviewUpForm.getModuleId(), entity);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 功能权限
     *
     * @param authorizeList  已有权限
     * @return
     */
    private AuthorizeDataReturnVO system(List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        List<SystemBaeModel> systemList = authorizeModel.getSystemList();
        // 哪些是系统的
        List<AuthorizeEntity> collect = authorizeList.stream().filter(t -> AuthorizeConst.SYSTEM.equals(t.getItemType())).collect(Collectors.toList());
        vo.setAll(systemList.stream().map(SystemBaeModel::getId).collect(Collectors.toList()));
        vo.setIds(collect.stream().map(AuthorizeEntity::getItemId).collect(Collectors.toList()));
        List<AuthorizeDataReturnModel> jsonToList = JsonUtil.getJsonToList(systemList, AuthorizeDataReturnModel.class);
        vo.setList(jsonToList);
        return vo;
    }


    /**
     * 功能权限
     *
     * @param moduleListAll  所有功能
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @param systemId 系统id
     * @return
     */
    private AuthorizeDataReturnVO module1(List<ModuleEntity> moduleListAll, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel, List<String> systemId) {
        UserInfo userInfo = UserProvider.getUser();
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        List<ModuleModel> moduleList = new ArrayList<>();
        if (!userInfo.getIsAdministrator()) {
            List<String> roleIds = new ArrayList<>();
            permissionGroupService.getPermissionGroupByUserId(userInfo.getUserId(), null, false).forEach(t -> {
                roleIds.add("'" + t.getId() + "'");
            });
            if (roleIds.size() != 0) {
                String roleIdsStr = String.join(",", roleIds);
                moduleList = authorizeMapper.findModule(roleIdsStr, null);
            }
        } else {
            moduleList = authorizeMapper.findModuleAdmin(1, null);
        }
        // 给顶级菜单设置父级节点
        moduleList.forEach(t -> {
            if ("-1".equals(t.getParentId())) {
                t.setParentId(t.getSystemId());
            }
        });

        // 得到系统信息放到菜单列表树种
        List<SystemBaeModel> systemList = authorizeModel.getSystemList();
        List<SystemBaeModel> collect = systemList.stream().filter(t -> systemId.contains(t.getId())).collect(Collectors.toList());
        List<ModuleModel> jsonToList = JsonUtil.getJsonToList(collect, ModuleModel.class);
        jsonToList.forEach(t -> t.setParentId("-1"));
        // 得到所有的东西
        List<String> collect3 = collect.stream().map(SystemBaeModel::getId).collect(Collectors.toList());
        moduleList = moduleList.stream().filter(t -> collect3.contains(t.getSystemId())).collect(Collectors.toList());
        moduleList.addAll(jsonToList);
        // 得到不同系统的appId数组
        int i = 1;
        List<String> appIds = new ArrayList<>(16);
        for (SystemBaeModel systemBaeModel : collect) {
            int finalI = i;
            moduleList.forEach(t -> {
                if ("App".equals(t.getCategory()) && systemBaeModel.getId().equals(t.getSystemId()) && "1".equals(String.valueOf(t.getType()))) {
                    t.setParentId("" + finalI);
                }
            });
            ModuleModel appData = new ModuleModel();
            appIds.add("" + i);
            appData.setId("" + i);
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setParentId(systemBaeModel.getId());
            moduleList.add(appData);
            i++;
        }
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        // 所有有权限的菜单
        List<AuthorizeEntity> collect1 = authorizeList.stream().filter(t -> "module".equals(t.getItemType())).collect(Collectors.toList());
        List<String> collect2 = collect1.stream().map(AuthorizeEntity::getItemId).collect(Collectors.toList());

        // 再次验证菜单id是否为当前系统下的
        List<String> list = new ArrayList<>();
        collect2.forEach(t -> {
            ModuleEntity info = moduleApi.getInfo(t);
            if (info != null) {
                if (collect3.contains(info.getSystemId())) {
                    list.add(t);
                }
            }
        });

        // 系统id也返回
        list.addAll(collect3);
        moduleModeId.addAll(list);
        List<AuthorizeDataModel> treeList = JsonUtil.getJsonToList(moduleList, AuthorizeDataModel.class);
        List<SumTree<AuthorizeDataModel>> trees = TreeDotUtils.convertListToTreeDot(treeList, "-1");
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        vo.setAll(moduleModeId.stream().distinct().collect(Collectors.toList()));
        list.addAll(appIds);
        vo.setIds(list.stream().filter(t -> list.contains(t)).distinct().collect(Collectors.toList()));
        vo.setList(data);
        return vo;
    }

    /**
     * 按钮权限
     *
     * @param moduleList     功能
     * @param moduleButton   按钮
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @return
     */
    AuthorizeDataReturnVO moduleButton(List<ModuleEntity> moduleList, List<ModuleButtonEntity> moduleButton, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ButtonModel> buttonList = authorizeModel.getButtonList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> buttonModeId = buttonList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(buttonModeId);
        List<String> ids = authorizeList.stream().filter(t -> "button".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ModuleEntity moduleEntity : moduleList) {
            for (ButtonModel buttonModel : buttonList) {
                if (buttonModel.getModuleId().equals(moduleEntity.getId())) {
                    AuthorizeModel treeModel = new AuthorizeModel();
                    treeModel.setId(buttonModel.getId());
                    treeModel.setFullName(buttonModel.getFullName());
                    treeModel.setIcon(buttonModel.getIcon());
                    if ("-1".equals(buttonModel.getParentId())) {
                        treeModel.setParentId(moduleEntity.getId());
                    } else {
                        boolean contains = buttonList.contains(buttonModel.getParentId());
                        if (!contains) {
                            continue;
                        }
                        treeModel.setParentId(buttonModel.getParentId());
                    }
                    treeList.add(treeModel);
                }
            }
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> buttonModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        moduleModeId.addAll(treeList.stream().map(AuthorizeModel::getId).collect(Collectors.toList()));
        vo.setAll(moduleModeId.stream().distinct().collect(Collectors.toList()));
        vo.setIds(ids.stream().filter(t -> moduleModeId.contains(t)).distinct().collect(Collectors.toList()));
        vo.setList(dataList);
        return vo;
    }

    /**
     * 列表权限
     *
     * @param moduleList       功能
     * @param moduleColumnList 列表
     * @param authorizeList    已有权限
     * @param authorizeModel   权限集合
     * @return
     */
    AuthorizeDataReturnVO moduleColumn(List<ModuleEntity> moduleList, List<ModuleColumnEntity> moduleColumnList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ColumnModel> columnList = authorizeModel.getColumnList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> columnModeId = columnList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(columnModeId);
        List<String> ids = authorizeList.stream().filter(t -> "column".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ModuleEntity moduleEntity : moduleList) {
            for (ColumnModel columnModel : columnList) {
                if (columnModel.getModuleId().equals(moduleEntity.getId())) {
                    AuthorizeModel treeModel = new AuthorizeModel();
                    treeModel.setId(columnModel.getId());
                    treeModel.setFullName(columnModel.getFullName());
                    treeModel.setIcon("fa fa-tags column");
                    treeModel.setParentId(columnModel.getModuleId());
                    treeList.add(treeModel);
                }
            }
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> columnModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        moduleModeId.addAll(treeList.stream().map(AuthorizeModel::getId).collect(Collectors.toList()));
        vo.setAll(moduleModeId.stream().distinct().collect(Collectors.toList()));
        vo.setIds(ids.stream().filter(t -> moduleModeId.contains(t)).distinct().collect(Collectors.toList()));
        vo.setList(dataList);
        return vo;
    }

    /**
     * 表单权限
     *
     * @param moduleList     功能
     * @param moduleFormList 表单列表
     * @param authorizeList  已有权限
     * @param authorizeModel 权限集合
     * @return
     */
    AuthorizeDataReturnVO moduleForm(List<ModuleEntity> moduleList, List<ModuleFormEntity> moduleFormList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ModuleFormModel> formList = authorizeModel.getFormsList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> formModeId = formList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(formModeId);
        List<String> ids = authorizeList.stream().filter(t -> "form".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ModuleEntity moduleEntity : moduleList) {
            for (ModuleFormModel columnModel : formList) {
                if (columnModel.getModuleId().equals(moduleEntity.getId())) {
                    AuthorizeModel treeModel = new AuthorizeModel();
                    treeModel.setId(columnModel.getId());
                    treeModel.setFullName(columnModel.getFullName());
                    treeModel.setIcon("fa fa-binoculars resource");
                    treeModel.setParentId(columnModel.getModuleId());
                    treeList.add(treeModel);
                }
            }
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> formModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        moduleModeId.addAll(treeList.stream().map(AuthorizeModel::getId).collect(Collectors.toList()));
        vo.setAll(moduleModeId.stream().distinct().collect(Collectors.toList()));
        vo.setIds(ids.stream().filter(t -> moduleModeId.contains(t)).distinct().collect(Collectors.toList()));
        vo.setList(dataList);
        return vo;
    }

    /**
     * 数据权限
     *
     * @param moduleList           功能
     * @param moduleDataSchemeList 数据方案
     * @param authorizeList        已有权限
     * @param authorizeModel       权限集合
     * @return
     */
    AuthorizeDataReturnVO resourceData(List<ModuleEntity> moduleList, List<ModuleDataAuthorizeSchemeEntity> moduleDataSchemeList, List<AuthorizeEntity> authorizeList, AuthorizeVO authorizeModel) {
        List<AuthorizeModel> treeList = new ArrayList<>();
        //appid
        List<String> appId = moduleList.stream().filter(t -> "App".equals(t.getCategory())).map(t -> t.getId()).collect(Collectors.toList());
        List<ResourceModel> resourceList = authorizeModel.getResourceList();
        List<String> moduleModeId = moduleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        List<String> resourceModeId = resourceList.stream().map(t -> t.getModuleId()).collect(Collectors.toList());
        moduleModeId.addAll(resourceModeId);
        List<String> ids = authorizeList.stream().filter(t -> "resource".equals(t.getItemType())).map(t -> t.getItemId()).collect(Collectors.toList());
        //获取按钮的菜单id
        for (ModuleEntity moduleEntity : moduleList) {
            for (ResourceModel resourceModel : resourceList) {
                if (resourceModel.getModuleId().equals(moduleEntity.getId())) {
                    AuthorizeModel treeModel = new AuthorizeModel();
                    treeModel.setId(resourceModel.getId());
                    treeModel.setFullName(resourceModel.getFullName());
                    treeModel.setIcon("fa fa-binoculars resource");
                    treeModel.setParentId(resourceModel.getModuleId());
                    treeList.add(treeModel);
                }
            }
        }
        List<ModuleEntity> list = moduleList.stream().filter(t -> resourceModeId.contains(t.getId())).collect(Collectors.toList());
        List<AuthorizeModel> moduleListAll = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(list, moduleList), AuthorizeModel.class);
        treeList.addAll(moduleListAll);
        treeList = treeList.stream().sorted(Comparator.comparing(AuthorizeModel::getSortCode)).collect(Collectors.toList());
        List<SumTree<AuthorizeModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<AuthorizeDataReturnModel> data = JsonUtil.getJsonToList(trees, AuthorizeDataReturnModel.class);
        List<AuthorizeDataReturnModel> dataList = new LinkedList<>();
        List<AuthorizeDataReturnModel> appChildList = new LinkedList<>();
        for (AuthorizeDataReturnModel model : data) {
            if (appId.contains(model.getId())) {
                appChildList.add(model);
            } else {
                dataList.add(model);
            }
        }
        if (appChildList.size() > 0) {
            AuthorizeDataReturnModel appData = new AuthorizeDataReturnModel();
            appData.setId("1");
            appData.setFullName("App菜单");
            appData.setIcon("ym-custom ym-custom-cellphone");
            appData.setChildren(appChildList);
            dataList.add(appData);
        }
        AuthorizeDataReturnVO vo = new AuthorizeDataReturnVO();
        moduleModeId.addAll(treeList.stream().map(AuthorizeModel::getId).collect(Collectors.toList()));
        vo.setAll(moduleModeId.stream().distinct().collect(Collectors.toList()));
        vo.setIds(ids.stream().filter(t -> moduleModeId.contains(t)).distinct().collect(Collectors.toList()));
        vo.setList(dataList);
        return vo;
    }

}
